package top.ddandang.blog.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.ddandang.blog.bean.WeChatBean;
import top.ddandang.blog.service.WeChatServer;
import top.ddandang.blog.utils.RedisUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author: D
 * @since: 2020/9/6
 * @version: 1
 */
@Service
public class WeChatServerImpl implements WeChatServer {

    @Resource
    WeChatBean weChatBean;

    @Resource
    RestTemplate restTemplate;

    @Resource
    RedisUtil redisUtil;

    /**
     * redis中存放access_token的key值
     */
    private final static String ACCESS_TOKEN_KEY = "accessToken";

    /**
     * redis中存放获取失败的错误信息的key值
     */
    private final static String ERROR_KEY = "accessToken";

    @Scheduled(initialDelay = 10000,fixedRate = 6600000)
    @Override
    public void creatAccessToken() {
        //String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx3c745d57091b1825&secret=479af32c2be2af00536fc27d6c469554";
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        String path = "?grant_type={grant_type}&appid={appid}&secret={secret}";
        Map<String, String> params = new HashMap<>(3);
        params.put("grant_type", "client_credential");
        params.put("appid", weChatBean.getAppId());
        params.put("secret", weChatBean.getSecret());
        ResponseEntity<String> forObject = restTemplate.getForEntity(url + path, String.class, params);
        System.out.println(forObject.getBody());
        JSONObject jsonObject = JSONObject.parseObject(forObject.getBody());
        String accessToken = jsonObject.getString("access_token");
        System.out.println(accessToken);
        // accessToken获取成功
        if (accessToken != null) {
            //有效期设置1小时55分钟
            redisUtil.set(ACCESS_TOKEN_KEY, accessToken, 115, TimeUnit.MINUTES);
        } else {
            redisUtil.set(ERROR_KEY, forObject.getBody());
        }
    }

    @Override
    public String getAccessToken() {
        //这大概率不会运行 除非redis连接失败或者蹦了
        if (!redisUtil.hasKey(ACCESS_TOKEN_KEY)) {
            throw new RuntimeException("获取失败，请稍后重试");
        }
        return (String) redisUtil.get(ACCESS_TOKEN_KEY);
    }
}
